<?php
/**
 * Created by PhpStorm.
 * User: moko1988
 * Date: 16/01/016
 * Time: 下午4:58
 */

namespace Admin\Controller;
use Think\Controller;

class MakehtmlController extends Controller {

    private $makeDir;

    public function _initialize(){

        $this->makeDir = str_replace("ThinkPHP/", '', THINK_PATH ).'Public/home/';//前台页面根目录

    }

    public function staticlist(){

        $list[] = ['name' => '首页', 'param' => '1'];
        $list[] = ['name' => '平台服务', 'param' => '2'];
        $list[] = ['name' => '新闻公告', 'param' => '3'];
        $list[] = ['name' => '关于我们', 'param' => '4'];

        $ajaxReturn['code'] 		= 1;
        $ajaxReturn['msg'] 			= "SUCCESS";
        $ajaxReturn['data']			= $list;

        $this->ajaxReturn($ajaxReturn);
    }

    public function create(){

        $makeType = I('post.makeType');

        $data = explode(',', $makeType);

        foreach($data as $k=>$v) {
            $this->switchMakeHtml($v);
        }

        $ajaxReturn['code'] 		= 1;
        $ajaxReturn['msg'] 			= "SUCCESS";

        $this->ajaxReturn($ajaxReturn);

    }



    protected function switchMakeHtml($type){
        switch ($type) {
            case 1 :  //创建首页
                $this->createIndex();
                break;
            case 2 :  //平台服务
                $this->createService();
                break;
            case 3 :  //新闻公告
                $this->createNews();
                break;
            case 4 :  //关于我们
                $this->createAboutus();
                break;
            default:break;
        }

    }

    /**
     * 生成首页
     */
    public function createIndex(){

        $Model = M();

        $sql = "SELECT a.litpic FROM __PICTURE__ AS a LEFT JOIN __PICTURE_CATEGORY__ AS b ON a.cid = b.id WHERE b.key = 'index-banner' ORDER BY a.rank DESC LIMIT 1";

        $result = $Model->query($sql);

        $indexBanner = C('PIC_PATH').$result[0]['litpic'];

        $this->assign('index_banner',$indexBanner);

        $con = $this->fetch('../Templets/index');

        $this->make('index.html', $con);

    }

    /**
     * 平台服务
     */
    public function createService(){

        $con = $this->fetch('../Templets/service');

        $this->createDir($this->makeDir . 'service');

        $this->make('service/index.html', $con);

    }


    /**
     * 关于我们
     */
    public function createAboutus(){

        $con = $this->fetch('../Templets/aboutus');

        $this->createDir($this->makeDir . 'aboutus');

        $this->make('aboutus/index.html', $con);

    }


    /**
     * 新闻公告
     */
    public function createNews(){

        $this->createArtType();

        $this->createArtInfo();

    }



    /**
     * 生成文章栏目页
     */
    public function createArtType(){

        $pageSize = 1;//每页展示数量

        $Model = M();

        $sql = "SELECT COUNT(*) AS dd FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE b.key = 'news-company' AND a.status = 1";

        $result = $Model->query($sql);

        $count = $result[0]['dd'];

        $totalPage = ceil($count/$pageSize);

        if($totalPage==0) $totalPage = 1;

        //循环生成分页列表
        for($page=1; $page<=$totalPage; $page++){

            $filePath = 'news';

            $fileName = $filePath.'/list_'.$page.'.html';

            $this->createDir(dirname($this->makeDir.$fileName));

            $limitStart = $pageSize*($page-1);

            $sql = "SELECT a.* FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE b.key = 'news-company' AND a.status = 1 ORDER BY a.rank desc LIMIT $limitStart,$pageSize";

            $list = $Model->query($sql);

            foreach($list as $k=>$v){

                $list[$k]['litpic'] = empty($v['litpic']) ? '/images/default.png' : C('PIC_PATH').$v['litpic'];

                $list[$k]['pubdate'] = date('Y-m-d H:i',$v['pubdate']);

                $list[$k]['arcurl'] = $this->GetArcUrl($v['id'],$v['pubdate']);


            }

            $this->assign('list',$list);

            //分页展示
            $tnamerule = $filePath.'/list_{page}.html';

            $pager = $this->GetPageList($page,$count,$totalPage,$tnamerule);

            $this->assign('pager',$pager);

            $sql = "SELECT a.* FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE b.key = 'news-industry' AND a.status = 1 ORDER BY a.rank desc LIMIT 15";

            $industry = $Model->query($sql);

            foreach($industry as $k=>$v){

                $industry[$k]['arcurl'] = $this->GetArcUrl($v['id'],$v['pubdate']);

            }

            $this->assign('industry',$industry);

            $sql = "SELECT a.* FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE a.status = 1 ORDER BY a.pubdate desc LIMIT 15";

            $new = $Model->query($sql);

            foreach($new as $k=>$v){

                $new[$k]['arcurl'] = $this->GetArcUrl($v['id'],$v['pubdate']);

            }

            $this->assign('new',$new);

            $con = $this->fetch('../Templets/news-list');

            $this->make($fileName, $con);

        }
        //复制列表页第一页为当前栏目的默认文件index.html
        $firstFileName = $this->makeDir.$filePath.'/list_1.html';
        $indexFileName = $this->makeDir.$filePath.'/index.html';
        copy($firstFileName,$indexFileName);
    }


    /**
     * 获取分页展示数据
     */
    public function GetPageList($PageNo,$TotalResult,$TotalPage,$TnameRule){

        $prepage = $nextpage = '';

        $prepagenum = $PageNo-1;

        $nextpagenum = $PageNo+1;

        $list_len=3;//分页列表宽度

        if($TotalPage<=1 && $TotalResult>0)
        {
            return "<span>共 <strong>1</strong>页<strong>".$TotalResult."</strong>条记录</span>\r\n";
        }

        if($TotalResult == 0)
        {
            return "<span>共 <strong>0</strong>页<strong>".$TotalResult."</strong>条记录</span>\r\n";
        }

        $maininfo = "<span>共 <strong>{$TotalPage}</strong>页<strong>".$TotalResult."</strong>条</span>\r\n";

        //获得上一页和主页的链接
        if($PageNo != 1)
        {
            $prepage .= "<a class=\"pre-next\" href='".str_replace("{page}",$prepagenum,$TnameRule)."'><<上一页</a>\r\n";

            $indexpage = "<a class=\"pre-next\" href='".str_replace("{page}",1,$TnameRule)."'>首页</a>\r\n";
        }
        else
        {
            $indexpage="<a class=\"pre-next\">首页</a>\r\n";
        }

        //下一页,未页的链接
        if($PageNo!=$TotalPage && $TotalPage>1)
        {
            $nextpage.="<a class=\"pre-next\" href='".str_replace("{page}",$nextpagenum,$TnameRule)."'>下一页>></a>\r\n";
            $endpage="<a class=\"pre-next\" href='".str_replace("{page}",$TotalPage,$TnameRule)."'>末页</a>\r\n";
        }
        else
        {
            $endpage="<a class=\"pre-next\">末页</a>\r\n";
        }

        //获得数字链接
        $listdd="";
        $total_list = $list_len * 2 + 1;//7
        if($PageNo >= $total_list)
        {
            $j = $PageNo-$list_len; //7
            $total_list = $PageNo+$list_len; //13
            if($total_list>$TotalPage)
            {
                $total_list=$TotalPage;
            }
        }
        else
        {
            $j=1;
            if($total_list>$TotalPage)
            {
                $total_list=$TotalPage;
            }
        }
        for($j;$j<=$total_list;$j++)
        {
            if($j==$PageNo)
            {
                $listdd.= "<a class=\"hover\">$j</a>\r\n";
            }
            else
            {
                $listdd.="<a href='".str_replace("{page}",$j,$TnameRule)."'>".$j."</a>\r\n";
            }
        }

        $plist = '';
        $plist .= $indexpage;
        $plist .= $prepage;
        $plist .= $listdd;
        $plist .= $nextpage;
        $plist .= $endpage;
        $plist .= $maininfo;

        return $plist;
    }


    /*
     * 获取文档的URL
     */
    public function GetArcUrl($aid,$pubdate){
        $typePath = '/news';
        $typePath .= '/'.date('Ym',$pubdate);
        $y = date('Y',$pubdate);
        $m = date('m',$pubdate);
        $d = date('d',$pubdate);
        $arcFileName = dd2char($m.$d.$aid.$y).'.html';

        return $typePath.'/'.$arcFileName;
    }

    /**
     * 生成文章内容页
     */
    public function createArtInfo(){

        $Model = M('Article');
        $arcList = $Model->where('status=1')->select();

        $sql = "SELECT a.* FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE b.key = 'news-industry' AND a.status = 1 ORDER BY a.rank desc LIMIT 15";

        $industry = $Model->query($sql);

        foreach($industry as $k=>$v){

            $industry[$k]['arcurl'] = $this->GetArcUrl($v['id'],$v['pubdate']);

        }

        $this->assign('industry',$industry);

        $sql = "SELECT a.* FROM __ARTICLE__ AS a LEFT JOIN __ARTICLE_CATEGORY__ AS b ON a.cid = b.id WHERE a.status = 1 ORDER BY a.pubdate desc LIMIT 15";

        $new = $Model->query($sql);

        foreach($new as $k=>$v){

            $new[$k]['arcurl'] = $this->GetArcUrl($v['id'],$v['pubdate']);

        }

        $this->assign('new',$new);

        //循环生成文章内容页
        foreach($arcList as $v){
            $this->valuePosition = array();

            $arcInfo = $Model->where('id='.$v['id'])->find();

            $filePath = $this->GetArcUrl($arcInfo['id'],$arcInfo['pubdate']);

            $arcInfo['pubdate'] = date('Y-m-d H:s',$arcInfo['pubdate']);

            $this->createDir(dirname($this->makeDir.$filePath));

            $this->assign('arcInfo',$arcInfo);

            $con = $this->fetch('../Templets/news-info');

            $this->make($filePath, $con);

        }
    }


    /**
     * 循环创建文件夹
     */
    protected function createDir($path){
        if (!file_exists($path)){
            $this->createDir(dirname($path));
            mkdir($path, 0777);
        }
    }

    /**
     * 存储静态页面
     */
    protected function make($fileName = null, $res){

        $fp = fopen($this->makeDir . $fileName, 'w');

        $fwirte = fwrite($fp, $res);

        fclose($fp);
        if ($fwirte > 0) {
            return true;
        }
        return false;
    }


}